package kd;

import javax.crypto.spec.*;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class Client2 {
    public static void main(String[] args) {
        Scanner inn = new Scanner(System.in);
        Socket mysocket;
        DataInputStream in = null;
        DataOutputStream out = null;
        try {
            mysocket = new Socket("127.1.0.0", 2010);
            in = new DataInputStream(mysocket.getInputStream());
            out = new DataOutputStream(mysocket.getOutputStream());
            KeyGenerator kg = KeyGenerator.getInstance("DESede");
            kg.init(168);
            SecretKey k = kg.generateKey();
            byte[] kb = k.getEncoded();
            System.out.println("请输入中缀表达式：");
            String infix = inn.nextLine();
            kd.MyBC1 myBC1 = new kd.MyBC1();
            String suffix = kd.MyBC1.infixToSuffix(infix);
            System.out.println(suffix);
            //中缀表达式加密
            Cipher cp = Cipher.getInstance("DESede");
            cp.init(Cipher.ENCRYPT_MODE, k);
            byte ptext[] = suffix.getBytes("UTF8");
            byte ctext[] = cp.doFinal(ptext);
            out.writeUTF(ctext.length + "");
            for (int i = 0; i < ctext.length; i++) {
                out.writeUTF(ctext[i] + "");
            }
            //对密钥进行加密
            kd.KeyAgree keyAgree = new kd.KeyAgree();
            SecretKeySpec k1 = keyAgree.KeyAgree("Serverpub.dat","Clientpri.dat");
            cp.init(Cipher.ENCRYPT_MODE, k1);
            byte ckey[] = cp.doFinal(kb);
            out.writeUTF(ckey.length + "");
            for (int i = 0; i < ckey.length; i++) {
                out.writeUTF(ckey[i] + "");
            }
            String result = in.readUTF();
            System.out.println("收到客户回答" + result);
            Thread.sleep(500);
        } catch (Exception e) {
            System.out.println("服务器已断开" + e);
        }
    }
}
